package org.dromara.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.BusinessException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.system.converter.MachineConverters;
import org.dromara.system.domain.SysUserCommonConfig;
import org.dromara.system.domain.bo.SysUserCommonConfigBo;
import org.dromara.system.domain.vo.SysUserCommonConfigVo;
import org.dromara.system.enums.MachineConstant;
import org.dromara.system.mapper.SysUserCommonConfigMapper;
import org.dromara.system.service.ISysUserCommonConfigService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 代理公共配置Service业务层处理
 *
 * @author Lion Li
 * @date 2025-07-03
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysUserCommonConfigServiceImpl extends ServiceImpl<SysUserCommonConfigMapper, SysUserCommonConfig> implements ISysUserCommonConfigService {


    /**
     * 查询代理公共配置
     *
     * @param id 主键
     * @return 代理公共配置
     */
    @Override
    public SysUserCommonConfigVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询代理公共配置列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 代理公共配置分页列表
     */
    @Override
    public TableDataInfo<SysUserCommonConfigVo> queryPageList(SysUserCommonConfigBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysUserCommonConfig> lqw = buildQueryWrapper(bo);
        Page<SysUserCommonConfigVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的代理公共配置列表
     *
     * @param bo 查询条件
     * @return 代理公共配置列表
     */
    @Override
    public List<SysUserCommonConfigVo> queryList(SysUserCommonConfigBo bo) {
        LambdaQueryWrapper<SysUserCommonConfig> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysUserCommonConfig> buildQueryWrapper(SysUserCommonConfigBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysUserCommonConfig> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(SysUserCommonConfig::getId);
        lqw.eq(bo.getUserId() != null, SysUserCommonConfig::getUserId, bo.getUserId());
        lqw.eq(bo.getRegisterPoints() != null, SysUserCommonConfig::getRegisterPoints, bo.getRegisterPoints());
        lqw.eq(bo.getMemberPrice() != null, SysUserCommonConfig::getMemberPrice, bo.getMemberPrice());
        lqw.eq(bo.getEveryAmount() != null, SysUserCommonConfig::getEveryAmount, bo.getEveryAmount());
        lqw.eq(bo.getCashBackPoints() != null, SysUserCommonConfig::getCashBackPoints, bo.getCashBackPoints());
        lqw.eq(bo.getPointsPeriodDay() != null, SysUserCommonConfig::getPointsPeriodDay, bo.getPointsPeriodDay());
        return lqw;
    }

    /**
     * 新增代理公共配置
     *
     * @param bo 代理公共配置
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SysUserCommonConfigBo bo) {
        SysUserCommonConfig add = MapstructUtils.convert(bo, SysUserCommonConfig.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改代理公共配置
     *
     * @param bo 代理公共配置
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SysUserCommonConfigBo bo) {
        SysUserCommonConfig update = MapstructUtils.convert(bo, SysUserCommonConfig.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysUserCommonConfig entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除代理公共配置信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public Boolean deploy(SysUserCommonConfigBo bo) {
        Long userId = bo.getUserId();
        SysUserCommonConfig sysUserCommonConfig = lambdaQuery().eq(SysUserCommonConfig::getUserId, userId).one();
        BusinessException.isNull(sysUserCommonConfig, "未查询到该条配置数据，联系管理员处理！");
        if (ObjectUtil.equal(bo.getTag(), MachineConstant.NUMBER.ONE)) {
            //修改注册赠送积分
            BigDecimal registerPoints = bo.getRegisterPoints();
            BusinessException.isNull(registerPoints, "积分未输入！");
            sysUserCommonConfig.setRegisterPoints(registerPoints);
        }
        if (ObjectUtil.equal(bo.getTag(), MachineConstant.NUMBER.TWO)) {
            //修改注册赠送积分
            BigDecimal memberPrice = bo.getMemberPrice();
            BusinessException.isNull(memberPrice, "开通VIP金额未输入！");
            sysUserCommonConfig.setMemberPrice(memberPrice);
        }
        if (ObjectUtil.equal(bo.getTag(), MachineConstant.NUMBER.THREE)) {
            //修改每交易X元赠送Y积分
            BigDecimal everyAmount = bo.getEveryAmount();
            BigDecimal cashBackPoints = bo.getCashBackPoints();
            BusinessException.isTrue(ObjectUtil.isNull(everyAmount) || ObjectUtil.isNull(cashBackPoints), "交易金额和返现积分不能为空！");
            sysUserCommonConfig.setEveryAmount(everyAmount);
            sysUserCommonConfig.setCashBackPoints(cashBackPoints);
        }
        if (ObjectUtil.equal(bo.getTag(), MachineConstant.NUMBER.FOUR)) {
            //修改积分有效期
            Integer pointsPeriodDay = bo.getPointsPeriodDay();
            BusinessException.isNull(pointsPeriodDay, "积分进账有效天数未输入！");
            sysUserCommonConfig.setPointsPeriodDay(pointsPeriodDay);
        }
        if (ObjectUtil.equal(bo.getTag(), MachineConstant.NUMBER.FIVE)) {
            //修改获取机具价格
            BigDecimal getMachinePrice = bo.getGetMachinePrice();
            BusinessException.isNull(getMachinePrice, "获取机具价格未输入！");
            sysUserCommonConfig.setGetMachinePrice(getMachinePrice);
        }
        if (ObjectUtil.equal(bo.getTag(), MachineConstant.NUMBER.SIX)) {
            //修改返现是否需要VIP
            Integer cashbackIsMember = bo.getCashBackIsMember();
            BusinessException.isNull(cashbackIsMember, "是否需要会员未输入！");
            sysUserCommonConfig.setCashBackIsMember(cashbackIsMember);
        }
        if (ObjectUtil.equal(bo.getTag(), MachineConstant.NUMBER.SEVEN)) {
            //修改提现单笔最小值和最大值
            BigDecimal withdrawalMin = bo.getWithdrawalMin();
            BusinessException.isNull(withdrawalMin, "单笔提现最小值未输入！");
            BigDecimal withdrawalMax = bo.getWithdrawalMax();
            sysUserCommonConfig.setWithdrawalMin(withdrawalMin);
            sysUserCommonConfig.setWithdrawalMax(withdrawalMax);

            //首笔起提金额
            BigDecimal firstWithdrawalMin = bo.getFirstWithdrawalMin();
            sysUserCommonConfig.setFirstWithdrawalMin(firstWithdrawalMin);
        }
        if (ObjectUtil.equal(bo.getTag(), MachineConstant.NUMBER.EIGHT)) {
            //修改商户单月最多提现总额
            BigDecimal withdrawalMaxMonth = bo.getWithdrawalMaxMonth();
            sysUserCommonConfig.setWithdrawalMaxMonth(withdrawalMaxMonth);
        }
        if (ObjectUtil.equal(bo.getTag(), MachineConstant.NUMBER.NINE)) {
            //修改抽奖保底金额
            BigDecimal lotteryMinimumGuaranteeReward = bo.getLotteryMinimumGuaranteeReward();
            sysUserCommonConfig.setLotteryMinimumGuaranteeReward(lotteryMinimumGuaranteeReward);
        }
        if (ObjectUtil.equal(bo.getTag(), MachineConstant.NUMBER.TEN)) {
            //修改抽奖保底金额
            BigDecimal prizeDrawPoints = bo.getPrizeDrawPoints();
            sysUserCommonConfig.setPrizeDrawPoints(prizeDrawPoints);
        }
        if (ObjectUtil.equal(bo.getTag(), MachineConstant.NUMBER.ELEVEN)) {
            //修改联系人地址
            String contactsImage = bo.getContactsImage();
            sysUserCommonConfig.setContactsImage(contactsImage);
        }
        return this.updateById(sysUserCommonConfig);
    }


    @Override
    public SysUserCommonConfigVo queryCommonConfig(Long userId) {
        SysUserCommonConfig sysUserCommonConfig = lambdaQuery().eq(SysUserCommonConfig::getUserId, userId).one();
        return MachineConverters.INSTANCE.toSysUserCommonConfigVo(sysUserCommonConfig);
    }

}
